package com.sky.service.impl;

import ch.qos.logback.core.util.MD5Util;
import com.sky.constant.MessageConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.entity.User;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import com.sky.vo.EmployeeLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        //判断用户是否存在,如果不存在添加到数据库中
        Employee employee = new Employee();
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5", employeeLoginDTO.getPassword());
             employee = employeeMapper.getByUsernameAndPassword(employeeLoginDTO.getUsername());
            if (employee == null) {
                employeeLoginDTO.setPassword(md5.toString());
                employeeMapper.insert(employeeLoginDTO);
            }
            if (!(md5.toString().equals(employee.getPassword()))){
                throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
            }

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId().toString())
                .name(employee.getName())
                .username(employee.getUsername())
                .build();
        return employeeLoginVO;
    }
}
